﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Senparc.NeuChar.Entities;
using Senparc.Weixin.MP.AppStore;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using WhoIsUnderCover.Controllers;

namespace WhoIsUnderCover.Models
{
    public class CustomMessageHandler : MessageHandler<WxCustomMessageContext>
    {
        private readonly UnderCoverContext _context;
        
        private static readonly string BaseAddress = "http://baidu.com";//ConfigurationManager.AppSettings["BaseAddress"];

        public CustomMessageHandler(Stream inputStream, PostModel postModel = null, int maxRecordCount = 0, DeveloperInfo developerInfo = null, UnderCoverContext context = null) 
            : base(inputStream, postModel, maxRecordCount, developerInfo)
        {
            _context = context;
        }

        public CustomMessageHandler(XDocument requestDocument, PostModel postModel = null, int maxRecordCount = 0, DeveloperInfo developerInfo = null, UnderCoverContext context = null) 
            : base(requestDocument, postModel, maxRecordCount, developerInfo)
        {
            _context = context;
        }

        public CustomMessageHandler(RequestMessageBase requestMessageBase, PostModel postModel = null, int maxRecordCount = 0, DeveloperInfo developerInfo = null, UnderCoverContext context = null) 
            : base(requestMessageBase, postModel, maxRecordCount, developerInfo)
        {
            _context = context;
        }


        public override void OnExecuted()
        {
            base.OnExecuted();
        }

        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            /* 
             * 所有没有被处理的消息会默认返回这里的结果
            */
            
            var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "";
            return responseMessage;
        }

        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            if (requestMessage.Content == "开房间")
            {
                return CreateRoom(requestMessage.FromUserName);
            }
            if(requestMessage.Content.Length==5)
            {
                Regex r = new Regex(@"^\d{6}$");
                if (r.Match(requestMessage.Content).Success)
                    return AddRoom(requestMessage.FromUserName, requestMessage.Content);
            }
            if (requestMessage.Content == "newwx")
            {
                return GetNewWeixin(requestMessage.FromUserName);
            }
            if (requestMessage.Content == "开始游戏")
            {
                return StartGame(requestMessage.FromUserName);
            }
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            //responseMessage.Content = "";// GetWelcomeInfo();
            //return responseMessage;

            //using (var ctx = new GdsfybjyWeiXinEntities())
            //{
            //   var list= ctx.KeywordReplies.Where(x => requestMessage.Content.Contains(x.Keyword));
            //   if (list.Any())
            //   {
            //       KeywordReply dbkeywordreply = list.OrderByDescending(x => x.Keyword.Length).First();


            //       var responseMessage = CreateResponseMessage<ResponseMessageText>();

            //       responseMessage.Content = dbkeywordreply.ReplyDesc.Trim();

            //       return responseMessage;
            //   }
            //}
            //将微信用户发来的消息转到多客服系统，由客服来处理。
            var responseMessage2 = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageTransfer_Customer_Service>(requestMessage);
            return responseMessage2;
        }



        /// <summary>
        /// 处理位置请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage)
        {
            //将微信用户发来的消息转到多客服系统，由客服来处理。
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageTransfer_Customer_Service>(requestMessage);
            return responseMessage;
        }

        /// <summary>
        /// 处理图片请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage)
        {
            //将微信用户发来的消息转到多客服系统，由客服来处理。
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageTransfer_Customer_Service>(requestMessage);
            return responseMessage;
        }

        /// <summary>
        /// 处理语音请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            //将微信用户发来的消息转到多客服系统，由客服来处理。
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageTransfer_Customer_Service>(requestMessage);
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            var responseMessage = ProcessMessage(requestMessage);
            return responseMessage;
        }

        private ResponseMessageText ProcessMessage(RequestMessageVoice message)
        {
            var recognition = message.Recognition;
            if (recognition.Contains("预约"))
            {
                return GetWxAppt(message.FromUserName);
            }
            else if (recognition.Contains("挂号单"))
            {
                return GetReport(message.FromUserName);
            }
            else if (recognition.Contains("挂号"))
            {
                return GetWxAppt(message.FromUserName);
            }
            else if (recognition.Contains("取号"))
            {
                return GetOtherAppt(message.FromUserName);
            }
            else if (recognition.Contains("号"))
            {
                return GetOtherAppt(message.FromUserName);
            }
            else if (recognition.Contains("候诊") || recognition.Contains("队列") || recognition.Contains("排队"))
            {
                return GetQueue(message.FromUserName);
            }
            else if (recognition.Contains("检验"))
            {
                return GetHealthReport(message.FromUserName);
            }
            else if (recognition.Contains("检查"))
            {
                return GetHealthReport(message.FromUserName);
            }
            else if (recognition.Contains("报告"))
            {
                return GetHealthReport(message.FromUserName);
            }
            else if (recognition.Contains("缴费") || recognition.Contains("交费") || recognition.Contains("费"))
            {
                return GetBill(message.FromUserName);
            }
            else if (recognition.Contains("就诊卡") || recognition.Contains("卡"))
            {
                return GetCard(message.FromUserName);
            }
            else if (recognition.Contains("满意"))
            {
                return GetServiceSiPaper(message.FromUserName);
            }
            else if (recognition.Contains("住院"))
            {
                return GetInpatientHistory(message.FromUserName);
            }
            else if (recognition.Contains("订餐"))
            {
                return CreateRoom(message.FromUserName);
            }
            else if (recognition.Contains("知识"))
            {
                return GetEducationInfo(message.FromUserName);
            }
            else if (recognition.Contains("咨询"))
            {
                return GetConsultationInfo(message.FromUserName);
            }
            else
            {
                var responseMessage = CreateResponseMessage<ResponseMessageText>();
                var result = new StringBuilder();

                var description = @"";
                result.Append(description).Append("很抱歉！我理解不了你的话语");
                responseMessage.Content = result.ToString();

                return responseMessage;
            }
        }

        /// <summary>
        /// 处理视频请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage)
        {
            //将微信用户发来的消息转到多客服系统，由客服来处理。
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageTransfer_Customer_Service>(requestMessage);
            return responseMessage;
        }

        /// <summary>
        /// 处理链接消息请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage)
        {
            //将微信用户发来的消息转到多客服系统，由客服来处理。
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageTransfer_Customer_Service>(requestMessage);
            return responseMessage;
        }

        /// <summary>
        /// 处理事件请求（这个方法一般不用重写，这里仅作为示例出现。除非需要在判断具体Event类型以外对Event信息进行统一操作
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var eventResponseMessage = base.OnEventRequest(requestMessage);//对于Event下属分类的重写方法，见：CustomerMessageHandler_Events.cs
            //TODO: 对Event信息进行统一操作
            return eventResponseMessage;
        }


        ///// <summary>
        ///// 订阅（关注）事件
        ///// </summary>
        //public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        //{
        //    var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
        //    responseMessage.Content = "感谢关注";

        //    return responseMessage;
        //}

        //public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        //{
        //    var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
        //    responseMessage.Content = "你好";
        //    return responseMessage;
        //}


        private string GetWelcomeInfo(string openId)
        {
            var wxuser = _context.wxUsers.Where(x => x.OpenId == openId).FirstOrDefault();
            if (wxuser == null)
            {
                var user = new WxUser
                {
                    OpenId = openId,
                    SubscribeDt = DateTime.Now,
                    RecStatus = 1,
                    RecCreateDt = DateTime.Now
                };
                _context.Add(user);
            }
            else
            {
                wxuser.SubscribeDt = DateTime.Now;
                
            }
            _context.SaveChanges();
            var info = $"欢迎关注。请使用下方菜单来进行你的游戏。如果可以，请推荐更多的人来玩，谢谢！";

            return info;
        }

        public override IResponseMessageBase OnTextOrEventRequest(RequestMessageText requestMessage)
        {
            // 预处理文字或事件类型请求。
            // 这个请求是一个比较特殊的请求，通常用于统一处理来自文字或菜单按钮的同一个执行逻辑，
            // 会在执行OnTextRequest或OnEventRequest之前触发，具有以下一些特征：
            // 1、如果返回null，则继续执行OnTextRequest或OnEventRequest
            // 2、如果返回不为null，则终止执行OnTextRequest或OnEventRequest，返回最终ResponseMessage
            // 3、如果是事件，则会将RequestMessageEvent自动转为RequestMessageText类型，其中RequestMessageText.Content就是RequestMessageEvent.EventKey

            return null;//返回null，则继续执行OnTextRequest或OnEventRequest
        }

        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            //微信用户openid
            var wxOpenId = requestMessage.FromUserName;

            IResponseMessageBase reponseMessage = null;
            //菜单点击，需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "hospital_info"://医院信息
                    reponseMessage = GetHospitalInfo(wxOpenId);
                    break;
                case "department_info"://科室信息
                    reponseMessage = GetDepartmentInfo(wxOpenId);
                    break;
                case "doctor_info"://医生信息
                    reponseMessage = GetDoctorInfo(wxOpenId);
                    break;
                case "notice_info"://医院公告
                    reponseMessage = GetHospNoticeInfo(wxOpenId);
                    break;
                case "service_guahao"://挂号
                    reponseMessage = GetWxAppt(wxOpenId);
                    break;
                case "service_quhao"://取号
                    reponseMessage = GetOtherAppt(wxOpenId);
                    break;
                case "service_hezhenduilie"://候诊队列
                    reponseMessage = GetQueue(wxOpenId);
                    break;
                case "service_jiuzhenjiaofei"://就诊缴费
                    reponseMessage = GetBill(wxOpenId);
                    break;
                case "service_qubaogaodan"://取报告单
                    reponseMessage = GetHealthReport(wxOpenId);
                    break;
                case "my_danju"://我的单据
                    reponseMessage = GetReport(wxOpenId);
                    break;
                case "my_juzhenka"://我的就诊卡
                    reponseMessage = GetCard(wxOpenId);
                    break;
                case "serviceDescription"://服务说明
                    reponseMessage = GetServiceDescription(wxOpenId);
                    break;
                case "service_manyidudiaocha"://满意度调查
                    reponseMessage = GetServiceSiPaper(wxOpenId);
                    break;
                case "service_inpatienthistory"://住院历史
                    reponseMessage = GetInpatientHistory(wxOpenId);
                    break;
                case "service_dinner": //订餐服务
                    reponseMessage = CreateRoom(wxOpenId);
                    break;
                default:
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "功能开发中，敬请期待！";
                    }
                    break;
            }

            return reponseMessage;
        }

        public override IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = "";
            return responseMessage;
        }

        public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = "";
            return responseMessage;
        }

        public override IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage)
        {
            //说明：这条消息只作为接收，下面的responseMessage到达不了客户端，类似OnEvent_UnsubscribeRequest
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "您点击了view按钮，将打开网页：" + requestMessage.EventKey;
            return responseMessage;
        }


        /// <summary>
        /// 扫描二维码绑卡，用户已关注微信时，调用此方法
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
        {
            var responseMessageContent = "";
            var eventKey = requestMessage.EventKey.Replace("qrscene_", "");
            var openId = requestMessage.FromUserName;
            var sceneId = Int64.Parse(eventKey);
            //HospCard card = null;
            //var resultCode = CardService.BindCardByScan(sceneId, openId, out card);
            //if (resultCode == 1)//超出最大绑卡数量
            //{
            //    responseMessageContent = "绑卡失败，原因：超出最大绑卡数量。\r\n如需帮助，请与客服联系。";
            //}
            //else if (resultCode == 2)
            //{
            //    responseMessageContent = "您已经添加过此就诊卡，请不要重复添加。\r\n如需帮助，请与客服联系。";
            //}
            //else if (resultCode == 0) //绑卡成功
            //{
            //    if (card != null)
            //    {
            //        var patientName = card.PatientName;
            //        var cardType = card.CardType == 0
            //            ? "诊疗卡"
            //            : card.CardType == 1 ? "健康卡" : card.CardType == 2 ? "市民卡" : "";
            //        var cardNo = card.CardNo;
            //        var sb = new StringBuilder();
            //        sb.Append("扫描二维码绑卡成功。您的就诊卡信息如下：\r\n");
            //        sb.AppendFormat("姓名：{0}", patientName).Append("\r\n");
            //        sb.AppendFormat("卡号：{0}", cardNo).Append("\r\n");
            //        sb.AppendFormat("卡类型：{0}", cardType).Append("\r\n");
            //        responseMessageContent = sb.ToString();
            //    }
            //}

            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = responseMessageContent;
            return responseMessage;


            //通过扫描关注
            //return base.OnEvent_ScanRequest(requestMessage);
        }


        /// <summary>
        /// 订阅（关注）事件。通过“EventKey”来区分用户是否是从带场景值的二维码来关注，如是，自动给用户绑定卡信息
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var now = DateTime.Now;
            var responseMessageContent = GetWelcomeInfo(requestMessage.FromUserName);
           
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = responseMessageContent;
            return responseMessage;

        }



        /// <summary>
        /// 退订
        /// 实际上用户无法收到非订阅账号的消息，所以这里可以随便写。
        /// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定，消除冗余数据。并且关注用户流失的情况。
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            //using (var ctx = new GdsfybjyWeiXinEntities())
            //{
            //    var user = ctx.Users.FirstOrDefault(p => p.OpenId == requestMessage.FromUserName);
            //    if (user != null)
            //    {
            //        var now = DateTime.Now;
            //        user.UnsubscribeDt = now;
            //        user.LastActiveDt = now;
            //        ctx.SaveChanges();
            //    }
            //}

            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "有空再来";
            return responseMessage;
        }


        public ResponseMessageNews GetHospitalInfo(string wxOpenId)
        {
            //微信openid签名，防止用户在url中伪造openid来访问
            //var wxSign = MD5SignUtil.Sign(wxOpenId, "gdsfybjy");

            var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "河源市中医院",
                Description = "二级甲等",
                PicUrl = BaseAddress + "/Images/hyzyy.jpg",
                Url = "" //MessageHelper.GetH5Url("/index/hosp-abstract")
            });
            //strongResponseMessage.Articles.Add(new Article()
            //{
            //    Title = "番禺院区",
            //    Description = "",
            //    PicUrl = "",
            //    Url = ""; //MessageHelper.GetH5Url("/index/branch-panyu")
            //});
            //strongResponseMessage.Articles.Add(new Article()
            //{
            //    Title = "越秀院区",
            //    Description = "",
            //    PicUrl = "",
            //    Url = ""; //MessageHelper.GetH5Url("/index/branch-yuexiu")
            //});
            //strongResponseMessage.Articles.Add(new Article()
            //{
            //    Title = "海珠院区",
            //    Description = "",
            //    PicUrl = "",
            //    Url = ""; //MessageHelper.GetH5Url("/index/branch-haizhu")
            //});


            return strongResponseMessage;
        }

        public ResponseMessageNews GetDepartmentInfo(string wxOpenId)
        {
            //微信openid验证签名，防止用户在url中伪造openid来访问
            //var wxSign = MD5SignUtil.Sign(wxOpenId, "gdsfybjy");

            var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "科室介绍",
                Description = "",
                PicUrl = BaseAddress + "/Images/ksjs.jpg",
                Url = "" //MessageHelper.GetH5Url("/index/depart-list?branchName=panyu&purpose=detail")
            });

            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "番禺院区",
                Description = "",
                PicUrl = "",
                Url = "" //MessageHelper.GetH5Url("/index/depart-list?branchName=panyu&purpose=detail")
            });
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "越秀院区",
                Description = "",
                PicUrl = "",
                Url = "" //MessageHelper.GetH5Url("/index/depart-list?branchName=yuexiu&purpose=detail")
            });
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "海珠院区",
                Description = "",
                PicUrl = "",
                Url = "" //MessageHelper.GetH5Url("/index/depart-list?branchName=haizhu&purpose=detail")
            });

            return strongResponseMessage;
        }

        public ResponseMessageNews GetDoctorInfo(string wxOpenId)
        {
            //微信openid验证签名，防止用户在url中伪造openid来访问
            //var wxSign = MD5SignUtil.Sign(wxOpenId, "gdsfybjy");

            var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "医生介绍",
                Description = "",
                PicUrl = BaseAddress + "/Images/ysjs.jpg",
                Url = ""
            });

            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "番禺院区",
                Description = "",
                PicUrl = "",
                Url = ""
            });
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "越秀院区",
                Description = "",
                PicUrl = "",
                Url = ""
            });
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "海珠院区",
                Description = "",
                PicUrl = "",
                Url = ""
            });

            return strongResponseMessage;
        }



        /// <summary>
        /// 在线挂号
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetWxAppt(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"在线挂号说明
1.您可挂当天或预约一周之内的医生号源。
2.挂号需绑定本院诊疗卡。
3.挂号支付成功后，请查阅“电子挂号单”，到指定诊室外等候呼叫、就诊。
4.如需退号，请凭“电子挂号单”到各楼层挂号处办理。
5.微信支付暂不支持退伍军人、老人、残疾人等减免政策。";

            var guaHaoUrl = ""; //MessageHelper.GetH5Url("/index/depart-list?branchName=panyu&purpose=appt");
 
            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【在线挂号】</a>", guaHaoUrl).Append("\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }



        /// <summary>
        /// 在线取号
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetOtherAppt(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"在线取号说明
1.在其他平台（官网、电话）预约，使用本院诊疗卡预约的取号以及医生诊间加号的取号。
2.如因您自身原因迟到，系统将自动安排您在本班次最后就诊或者退号重新现场挂号。";
            //4.如需退预约号，请于支付当天晚12点前办理，超时请在就诊日期前移步就诊院区的人工窗口办理。";

            var url = ""; //MessageHelper.GetH5Url("/index/get-other-appt");

            result.Append(description).Append("\r\n\r\n"); ;
            result.AppendFormat("<a href=\"{0}\">点这里【在线取号】</a>", url);
            responseMessage.Content = result.ToString();

            return responseMessage;
        }


        /// <summary>
        /// 候诊队列
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetQueue(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"候诊队列说明
1.候诊队列支持实时查询候诊信息，可能因网络延时等原因造成信息不一致，微信查询仅供参考，请以现场候诊队列信息为准。";

            var url = ""; //MessageHelper.GetH5Url("/index/get-queue");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里查看【候诊队列】</a>", url).Append("\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }



        /// <summary>
        /// 就诊缴费
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetBill(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"就诊缴费说明
1.缴费提供微信支付。
2.处方单当天缴费有效。
3.目前微信支付只提供自费病人缴费，普通门诊医保统筹记账缴费（仅开通妇科门诊医保自助缴费，自付部分按自费缴费）、门慢医保、门特医保、公费医疗在微信支付按自费缴费，如需记账请移步到各楼层收费窗口进行缴费。
4.如需打印发票或办理退费请凭微信缴费“电子凭条”到各楼层收费处办理。
5.如需打印费用清单请凭发票到前线服务打印。";

            var url = ""; //MessageHelper.GetH5Url("/index/get-bill");

            result.Append(description).Append("\r\n\r\n"); ;
            result.AppendFormat("<a href=\"{0}\">点这里【就诊缴费】</a>", url).Append("\r\n"); ;

            responseMessage.Content = result.ToString();

            return responseMessage;
        }


        /// <summary>
        /// 取报告单
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetHealthReport(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"报告单说明
1.默认可以查询一个月的检查/检验单。
2.可以筛选自开始日期起10天内的检查/检验单。
3.本检查单/检验单仅供参考。
4.若有需要请到医院提取纸质报告单或使用自助机打印。";

            var checkUrl = ""; //MessageHelper.GetH5Url("/index/get-check");
            var inspectionUrl = ""; //MessageHelper.GetH5Url("/index/get-inspection");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【取检查单】</a>", checkUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【取检验单】</a>", inspectionUrl).Append("\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }



        /// <summary>
        /// 我的单据
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetReport(string wxOpenId)
        {
            //微信openid验证签名，防止用户在url中伪造openid来访问
            //var wxSign = MD5SignUtil.Sign(wxOpenId, "gdsfybjy");

            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"我的单据说明
1. 挂号单：可以查询此微信号缴过的挂号单明细信息。
2. 缴费单： 可以查询此微信号缴过的缴费单明细信息。
3. 预交金单：可以查询此微信号交过的预交金单信息。
4. 点餐订单：可以查询此微信号订过的点餐订单信息。";

            var apptRegOrderUrl = ""; //MessageHelper.GetH5Url("/index/reg-order-list");
            var paidBillUrl = ""; //MessageHelper.GetH5Url("/index/bill-order-list");
            var inpatientPrepayUrl = ""; //MessageHelper.GetH5Url("/index/prepay-order-list");
            var dinnerUrl = ""; //MessageHelper.GetH5Url("/index/dinner-order-list");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询挂号单】</a>", apptRegOrderUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询缴费单】</a>", paidBillUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询住院预交金记录】</a>", inpatientPrepayUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询点餐记录】</a>", dinnerUrl).Append("\r\n");

            responseMessage.Content = result.ToString();
            return responseMessage;
        }



        /// <summary>
        /// 我的就诊卡
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetCard(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"我的就诊卡说明
以下情况可在“管理就诊卡”进行绑定
1.有我院诊疗卡
2.有广州市健康卡并且已绑定我院就诊卡
除此之外，如还无诊疗卡可以在“管理就诊卡”进行初诊建卡或到我院门诊一楼前线服务，办理诊疗卡或广州市健康卡。";

            var url = ""; //MessageHelper.GetH5Url("/index/manage-card");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【管理就诊卡】</a>", url).Append("\r\n"); ;

            responseMessage.Content = result.ToString();

            return responseMessage;
        }


        /// <summary>
        /// 服务说明
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetServiceDescription(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"";

            var url = ""; //MessageHelper.GetH5Url("/index/hosp-service-desc");

            result.Append(description).Append("");
            result.AppendFormat("<a href=\"{0}\">点这里查看【服务说明】</a>", url).Append("\r\n"); ;

            responseMessage.Content = result.ToString();

            return responseMessage;
        }

        /// <summary>
        /// 满意度调查
        /// </summary>
        /// <returns></returns>
        public ResponseMessageText GetServiceSiPaper(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"";

            var url = ""; //MessageHelper.GetH5Url("/index/paper-list");

            result.Append(description).Append("");
            result.AppendFormat("<a href=\"{0}\">点这里【满意度调查】</a>", url).Append("\r\n"); ;

            responseMessage.Content = result.ToString();

            return responseMessage;
        }

        /// <summary>
        /// 医院公告
        /// </summary>
        /// <returns></returns>
        public ResponseMessageNews GetHospNoticeInfo(string wxOpenId)
        {
            var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            strongResponseMessage.Articles.Add(new Article()
            {
                Title = "医院公告",
                Description = "",
                PicUrl = "",
                Url = ""
            });

            

            

            return strongResponseMessage;
        }


        /// <summary>
        /// 住院历史信息
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public ResponseMessageText GetInpatientHistory(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var description = @"服务说明：
1、住院每日清单查询。
2、住院预交金充值。";
            //3、查询住院报告。";

            var url = ""; //MessageHelper.GetH5Url("/index/get-inpatient"); ;

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里办理【住院服务】</a>", url).Append("\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }

        /// <summary>
        /// 创建房间
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public ResponseMessageText CreateRoom(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = "";

            Random rd = new Random();
            bool createSuccess = false;
            while (!createSuccess)
            {
                var radomNum = rd.Next(10000, 99999);
                var roomNum = string.Format("{0:000000}", radomNum);
                var room = _context.rooms.Where(x => x.RoomNum == roomNum).FirstOrDefault();
                if (room == null)
                {
                    var newRoom = new Room
                    {
                        CreateOpenId = wxOpenId,
                        RoomNum = roomNum,
                        RecCreateDt = DateTime.Now,
                        RecStatus = 1
                    };
                    _context.rooms.Add(newRoom);
                    createSuccess = true;
                    result = $"创建成功！房间号：{roomNum},快让你的朋友给我回复该房间号进入游戏吧！";

                    var user = _context.wxUsers.Where(x=>x.OpenId==wxOpenId).FirstOrDefault();
                    user.InRoomNum = roomNum;
                    user.RecUpdateDt = DateTime.Now;

                    _context.SaveChangesAsync();
                }
            }
            responseMessage.Content = result.ToString();
            return responseMessage;
        }

        /// <summary>
        /// 加入房间
        /// </summary>
        /// <param name="wxOpenId">用户ID</param>
        /// <returns></returns>
        public ResponseMessageText AddRoom(string wxOpenId,string roomNum)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = "";

            var addroom = _context.rooms.Where(x=>x.RoomNum==roomNum).FirstOrDefault();

            if(addroom==null)
            {
                result = "加入房间失败，请再次确认房间号！";
            }

            var user = _context.wxUsers.Where(x => x.OpenId == wxOpenId).FirstOrDefault();
            user.InRoomNum = roomNum;
            user.RecUpdateDt = DateTime.Now;
            _context.SaveChanges();

            var userNum = _context.wxUsers.Where(x=>x.InRoomNum==roomNum).Count();
            result = $"加入房间成功！该房间目前有{userNum}人！";
            responseMessage.Content = result.ToString();
            return responseMessage;
        }

        /// <summary>
        /// 开始游戏
        /// </summary>
        /// <param name="wxOpenId">用户ID</param>
        /// <returns></returns>
        public ResponseMessageText StartGame(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = "";

            var addroom = _context.rooms.Where(x => x.CreateOpenId == wxOpenId).OrderByDescending(x=>x.Id).FirstOrDefault();
            var user = _context.wxUsers.Where(x => x.OpenId == wxOpenId).FirstOrDefault();
            if (addroom == null || (addroom.RoomNum!=user.InRoomNum))
            {
                result = "您不是房主哦，不能开始游戏呢！";
            }
            


            responseMessage.Content = result.ToString();
            return responseMessage;
        }

        /// <summary>
        /// 宣教知识信息
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public ResponseMessageText GetEducationInfo(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();

            var url = ""; //MessageHelper.GetH5Url("/index/education-type");

            result.AppendFormat("<a href=\"{0}\">点这里查看【宣教知识】</a>", url).Append("\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }
        /// <summary>
        /// 在线咨询
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public ResponseMessageText GetConsultationInfo(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();
            var url = "";

            //result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【在线咨询】</a>", url).Append("\r\n\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }


        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public ResponseMessageText GetNewWeixin(string wxOpenId)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            var result = new StringBuilder();
            var url = @"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx98fca627995d473f&redirect_uri=http%3A%2F%2Fwx.e3861.com%2Fapi%2FAuth%2FWxOauth2%3Furl%3Dhttp%253a%252f%252fwx.e3861.com%252fh5%252findex.html%2523%21&response_type=code&scope=snsapi_userinfo&state=GbkYin666#wechat_redirect";

            result.AppendFormat("<a href=\"{0}\">点这里【XINWEIXIN】</a>", url).Append("\r\n\r\n");

            responseMessage.Content = result.ToString();

            return responseMessage;
        }

    }
   
}